'''
  实现一个单向链表
'''

class Node:
	def __init__(self, data=None):
		self.data = data
		self.next = None

class Linklist:
	def __init__(self):
		self.head = None
		self.length = 0
	def __len__(self):
		return self.length
	def __str__(self):
		return 'single link list'
	def __iter__(self):
		self.start = self.head
		return self
	def __next__(self):
		if self.start == None:
			raise StopIteration
		ret = self.start.data
		self.start = self.start.next
		return ret
	def __setitem__(self, i, node):
		if i > self.length:
			return
		if i == 0:
			node.next = self.head
			self.head = node
			return
		pre = self.get_pre_node(i)
		node.next = pre.next
		pre.next = node
		return
	def __delitem__(self, i):
		if i + 1 > self.length:
			return
		if i == 0:
			self.head = self.head.next
			return
		pre = self.get_pre_node(i)
		pre.next = pre.next.next
	def __getitem__(self, i):
		if i+1 > self.length:
			return None
		ret = self.head
		while i != 0:
			ret = ret.next
			i -= 1
		return ret
	def append(self, node, tohead=True):
		self.length += 1
		if self.head == None:
			self.head = node
			return self.length
		if tohead:
			node.next = self.head
			self.head = node
			return self.length
		last = self.get_last()
		last.next = node
		return self.length
	def sort(self):
		pass
	def get_last(self):
		pre, temp = None, self.head
		while temp != None:
			pre = temp
			temp = temp.next
		return pre
	def get_pre_node(self, i):
		if i > self.length:
			return None
		pre, temp = None, self.head
		while i != 0 and temp != None:
			pre = temp
			temp = temp.next
			i -= 1
		return pre

if __name__ == '__main__':
	print('testing...')
	mylist = Linklist()
	mylist.append(Node(0), False)
	mylist.append(Node(1), False)
	mylist.append(Node(2), False)
	mylist.append(Node(3), False)
	for x in mylist:
		print(x)
	print('len = {}'.format(len(mylist)))
	mylist[5] = Node('erick')
	for x in mylist:
		print(x)
	print('len = {}'.format(len(mylist)))

